package com.schedualnew.mq.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.schedualnew.mq.config.AppParamsConfig;
import com.schedualnew.mq.constvalue.ActTypeConstValue;
import com.schedualnew.mq.dto.common.Res;
import com.schedualnew.mq.dto.common.apply.ApplyExaminationRequestVo;
import com.schedualnew.mq.dto.common.apply.ChangeExaminationStatusRequestVo2;
import com.schedualnew.mq.dto.common.apply.GetApplyInfoInput;
import com.schedualnew.mq.dto.esb.*;
import com.schedualnew.mq.dto.esb.mq.send.SendESBEntry;
import com.schedualnew.mq.dto.esb.mq.send.SendMsg;
import com.schedualnew.mq.dto.esb.mq.send.SendMsgInfo;
import com.schedualnew.mq.dto.exam.ExamApplyDto;
import com.schedualnew.mq.dto.exam.ExamApplyItemDto;
import com.schedualnew.mq.dto.notice.NoticeRootDto;
import com.schedualnew.mq.entity.ExamApply;
import com.schedualnew.mq.entity.vo.ExamScheduleItemVo;
import com.schedualnew.mq.mapper.ExamApplyItemMapper;
import com.schedualnew.mq.mapper.ExamApplyMapper;
import com.schedualnew.mq.mapper.ExamScheduleItemMapper;
import com.schedualnew.mq.service.CommonService;
import com.schedualnew.mq.service.MQClientService;
import com.schedualnew.mq.service.XRayService;
import com.schedualnew.mq.util.HLHTUtil;
import com.schedualnew.mq.util.JacksonUtil;
import com.schedualnew.mq.util.RequestClientUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("api/schedule/mq")
public class MQApiController {

    private Logger logger = LogManager.getLogger(MQApiController.class);

    @Autowired
    private MQClientService mqClientService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private ExamApplyMapper examApplyMapper;

    @Autowired
    private ExamApplyItemMapper examApplyItemMapper;

    @Autowired
    private XRayService xRayService;

    @Value("${applymq.pushToHLHT}")
    private String pubshToHLHT;

    @Value("${applymq.HLHTUrl}")
    private String hlhtUrl;

    private String needPushHLHT = "1";

    @RequestMapping("test")
    public Res test() {
        try {
            //mqClientService.pushMsg("tete", "");
        } catch (Exception e) {

        }

        try {
            boolean msg = mqClientService.listenReceiveMessage("tete", "", "", entity -> {
                logger.info(JSONUtil.toJsonStr(entity));
            });
        } catch (Exception e) {

        }

        return Res.Success();
    }


    @RequestMapping("applyExamination")
    public Res applyExamination(@RequestBody ApplyExaminationRequestVo requestVo) {

        ApplyExaminationMsg msg = new ApplyExaminationMsg();


        ESBEntry esbEntry = new ESBEntry();

        // mqClientService.pushMsg();

        return Res.Success();
    }

    @RequestMapping("changeExaminationStatus2")
    public Res changeExaminationStatus2(@RequestBody ChangeExaminationStatusRequestVo2 requestVo) {
        logger.info("请求参数:" + JSONUtil.toJsonStr(requestVo));
        List<String> result = new ArrayList<>();
        // 多个申请合并预约的情况需要分开推送
        if (!CollectionUtils.isEmpty(requestVo.getApplyNos()) && requestVo.getApplyNos().size() > 1) {
            for (String applyNo : requestVo.getApplyNos()) {
                ChangeExaminationStatusRequestVo2 requestVo2 = BeanUtil.copyProperties(requestVo, ChangeExaminationStatusRequestVo2.class);
                requestVo2.setApplyNos(null);
                requestVo2.setApplyNo(applyNo);
                requestVo2.setActType(requestVo.getActType());

                String resultStr = commonService.pushStatusMsg(requestVo2);
                result.add(resultStr);

                pushHLHT(applyNo,requestVo.getActType());
            }
        } else {
            String resultStr = commonService.pushStatusMsg(requestVo);
            result.add(resultStr);

            pushHLHT(requestVo.getApplyNo(),requestVo.getActType());
        }
        logger.info("changeExaminationStatus2执行结果:{}", JSONUtil.toJsonStr(result));
        return Res.Success();
    }

    private  void pushHLHT(String applyNo,String actType)
    {
        //推送申请单状态更新到互联互通接口
        if (needPushHLHT.equals(pubshToHLHT)) {
            try {
                logger.info("开始同步到互联互通");
                ExamApplyDto queryInput = new ExamApplyDto();
                queryInput.setApplyNo(applyNo);
                logger.info("applyNo:" + applyNo);
                ExamApplyDto examApply = examApplyMapper.getExamApply(queryInput);
                String xml ="";
                if("0".equals(actType)) {
                    xml=new HLHTUtil().loadAppointXML(examApply);
                }
                else
                {
                    xml=new HLHTUtil().loadXML(examApply);
                }
                logger.info("examApply:" + JSONUtil.toJsonStr(examApply));
                logger.info("互联互通xml:" + xml);
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(xml) && Objects.nonNull(examApply)) {
                    String action = "CheckAppointStatusInfoUpdate";
                    String soapContent=LoadSoapXml(action,xml);
                    logger.info("互联互通soapContent:" + soapContent);
                    new RequestClientUtil().sendSoapRequest(soapContent, action, hlhtUrl);
                }
            } catch (Exception ex) {
                logger.info("互联互通不同出错:" + applyNo + ex.toString());
            }
        }
    }

    private String LoadSoapXml(String action, String conetnt) {
        String xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:hl7-org:v3\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <urn:HIPMessageServer>\n" +
                "         <action>" + action + "</action>\n" +
                "         <message><![CDATA[" + conetnt + "]]></message>\n" +
                "      </urn:HIPMessageServer>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        return xml;
    }


    private ApplyExaminationMsg vo2EsbEntity(ApplyExaminationRequestVo requestVo) {
        ApplyExaminationMsg msg = new ApplyExaminationMsg();
        msg.setAction("insert");
        msg.setId("1111111");
        msg.setLastUpdate(DateUtil.format(new Date(), "YYYY"));


        return msg;

    }


    /**
     * 根据申请单号查询申请单信息
     *
     * @param input
     * @return
     */
    @PostMapping("getApplyInfo")
    public Res getApplyInfo(@RequestBody GetApplyInfoInput input) {
        logger.info("请求参数:" + JSONUtil.toJsonStr(input));
        ExamApplyDto queryInput = new ExamApplyDto();
        queryInput.setApplyNo(input.getApplyNo());
        ExamApplyDto examApply = examApplyMapper.getExamApply(queryInput);
        if (Objects.nonNull(examApply)) {
            ExamApplyItemDto itemQueryInput = new ExamApplyItemDto();
            itemQueryInput.setApplyNo(input.getApplyNo());
            List<ExamApplyItemDto> itemDtos = examApplyItemMapper.getList(itemQueryInput);
            examApply.setItems(itemDtos);
        }
        logger.info("getApplyInfo执行结果:{}", JSONUtil.toJsonStr(examApply));
        return Res.Success(examApply);
    }
}
